package com.vancouver.knows.ui.fragment.citynews;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.pangu.bean.PageInfo;
import com.pangu.service.ActionException;
import com.pangu.task.mark.ATaskMark;
import com.pangu.ui.browser.PullListItemBrowser;
import com.pangu.ui.refresh.ARefreshViewController;
import com.pangu.util.DeviceUtil;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.MainApplication.TrackerName;
import com.vancouver.knows.business.cache.CityNewsInfoCache;
import com.vancouver.knows.ui.activity.citynews.CityNewsDetailActivity;
import com.vancouver.knows.ui.view.CoverImageView;
import com.vancouver.knows.util.AnalyticsConstants;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.CityNewsInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.FetchCityNewsTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteUpvoteTaskMark;
import com.vancouver.knows.business.task.mark.UserUpvoteTaskMark;
import com.vancouver.knows.util.CircleTransform;

import java.util.ArrayList;
import java.util.List;

public class CityNewsListView extends PullListItemBrowser<MainApplication> {

	private BusinessModule bModule;
	private final int ITEM_TYPE_USER_POST = 1;
	private final int ITEM_TYPE_POST = 0;

	@Override
	protected View createLoadingView(Context context) {
		RelativeLayout loadingView = (RelativeLayout) super.createLoadingView(context);
		LayoutParams linearLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		ImageView loadingImageView = new ImageView(context);
		loadingImageView.setLayoutParams(linearLayoutParams);
		loadingImageView.setImageResource(R.drawable.loading_city_news);
		loadingImageView.setScaleType(ImageView.ScaleType.FIT_XY);
		loadingView.addView(loadingImageView, 0);
		return loadingView;
	}

	public CityNewsListView(Context context, ARefreshViewController mController) {
		super(context, mController);
		init();
	}

	public CityNewsListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		bModule = imContext.getBusinessModule();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Intent intent = new Intent(getContext(), CityNewsDetailActivity.class);
		CityNewsInfo cityNewsInfo = (CityNewsInfo) ((CityNewsAdapter) getAdapterView().getAdapter()).getItem(position);
		intent.putExtra("postId", cityNewsInfo.getId());
		getContext().startActivity(intent);

		Tracker t = ((MainApplication) ((Activity) getContext()).getApplication()).getTracker(TrackerName.APP_TRACKER);
		t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_CITYNEWS);
		t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_BTN)
				.setAction(AnalyticsConstants.ACTION_ONCLICK).setLabel(cityNewsInfo.getTitle()).build());
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		return false;
	}

	@Override
	protected BaseAdapter createAdapter() {
		return new CityNewsAdapter();
	}

	public void initLoadableView(ATaskMark taskWraper) {
		super.initLoadableView(taskWraper);
	}

	@Override
	protected void setListViewParameters(ListView listView) {
		super.setListViewParameters(listView);

		listView.setDivider(new ColorDrawable(getResources().getColor(R.color.line_color))); //common_bg
		listView.setDividerHeight(1);
	}

	@Override
	protected void handleLoadNewItems(ATaskMark taskMark) {
		FetchCityNewsTaskMark fetchCityNewsTaskMark = (FetchCityNewsTaskMark) taskMark;
		bModule.getServiceWrapper().fetchCityNews(this,fetchCityNewsTaskMark.getOrder(),
				fetchCityNewsTaskMark.getCategory(), AppUtils.getUserId(bModule));
	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		super.receiveResult(taskMark, exception, trackerResult);

		if ((taskMark instanceof UserUpvoteTaskMark || taskMark instanceof UserDeleteUpvoteTaskMark)
				&& taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
			notifyDataSetChanged();
		}
	}

	public class CityNewsAdapter extends BaseAdapter {

		private LayoutInflater inflater;

		public CityNewsAdapter() {
			inflater = LayoutInflater.from(getContext());
		}

		@Override
		public int getCount() {
			return bModule.getCacheManager().getCityNewsInfoCache().getItemInfoCount(mTaskMark);
		}

		@Override
		public CityNewsInfo getItem(int position) {
			return bModule.getCacheManager().getCityNewsInfoCache().getItemInfoByTypeIndex(mTaskMark, position);
		}

		@Override
		public int getItemViewType(int position) {
			CityNewsInfo cityNewsInfo = getItem(position);
			if("userpost".equals(cityNewsInfo.getType())){
				return ITEM_TYPE_USER_POST;
			}else{
				return ITEM_TYPE_POST;
			}
		}

		@Override
		public int getViewTypeCount() {
			return 2;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (position == (getCount() - 1)) {
				tryQueryNewItems(true, ATaskMark.TYPE_DEFAULT);
			}

			int type = getItemViewType(position);

			if (convertView == null) {
				convertView = createItemView(parent,type);
			}

			CityNewsInfo cityNewsInfo = getItem(position);
			if (cityNewsInfo != null) {
				initItemView(convertView, cityNewsInfo,type);
			}

			return convertView;
		}

		private View createItemView(ViewGroup parent,int type) {
			View view;
			if(ITEM_TYPE_POST == type){
				view = inflater.inflate(R.layout.citynews_item_editor, parent, false);
				EditorViewHolder viewHolder = new EditorViewHolder(view);
				view.setTag(viewHolder);

			}else{
				view = inflater.inflate(R.layout.citynews_item_user, parent, false);
				ViewHolder viewHolder = new ViewHolder(view);
				view.setTag(viewHolder);
			}
			return view;
		}

		private void initEditorItemView(View convertView, CityNewsInfo cityNewsInfo){
			EditorViewHolder viewHolder = (EditorViewHolder) convertView.getTag();
			Picasso.with(imContext).load(cityNewsInfo.getSourceImage())
					.transform(new CircleTransform())
					.placeholder(R.drawable.no_avatar)
					.resizeDimen(R.dimen.city_list_head_size, R.dimen.city_list_head_size)
					.into(viewHolder.header);
			if(StringUtil.isEmptyString(cityNewsInfo.getSourceName())){
				viewHolder.source.setText(R.string.app_name);
				viewHolder.author.setText(createEditorAuthorStr(cityNewsInfo));
				viewHolder.title.setText(cityNewsInfo.getTitle());
				//viewHolder.content.setText(cityNewsInfo.getContentSummary());
				if (!StringUtil.isEmptyString(cityNewsInfo.getAttachmentImage())) {
					Picasso.with(imContext).load(cityNewsInfo.getAttachmentImage()).placeholder(R.drawable.no_image)
							.centerCrop().resizeDimen(R.dimen.citynews_item_img_width, R.dimen.citynews_item_img_height)
							.into(viewHolder.attachmentImage);
				} else {
					viewHolder.attachmentImage.setImageResource(R.drawable.no_image);
				}

			}else{
				viewHolder.source.setText(cityNewsInfo.getSourceName());
				viewHolder.author.setText(createEditorAuthorStr(cityNewsInfo));
				viewHolder.title.setText(cityNewsInfo.getTitle());
				//viewHolder.content.setText(cityNewsInfo.getContentSummary());
				if (!StringUtil.isEmptyString(cityNewsInfo.getAttachmentImage())) {
					Picasso.with(imContext).load(cityNewsInfo.getAttachmentImage()).placeholder(R.drawable.no_image)
							.centerCrop().resizeDimen(R.dimen.citynews_item_img_width, R.dimen.citynews_item_img_height)
							.into(viewHolder.attachmentImage);
				} else {
					viewHolder.attachmentImage.setImageResource(R.drawable.no_image);
				}
			}
//			if ("Y".equals(cityNewsInfo.getUserUpvoted())) {
//				Drawable drawable = getResources().getDrawable(R.drawable.citynews_item_icon_like_active);
//				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//				viewHolder.upvote.setCompoundDrawables(drawable,null , null, null);
//
//			}else{
//				Drawable drawable = getResources().getDrawable(R.drawable.citynews_item_icon_like);
//				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//				viewHolder.upvote.setCompoundDrawables(drawable,null , null, null);
//			}

			viewHolder.upvote.setTag(cityNewsInfo);
			viewHolder.upvote.setText(" " + getContext().getString(R.string.dot)+ " "
					+ cityNewsInfo.getUpvoteCount()
					+ getResources().getString(R.string.dot_upvote));

			viewHolder.commentCount.setTag(cityNewsInfo);
			viewHolder.commentCount.setText(" " + getContext().getString(R.string.dot)+ " "
					+ cityNewsInfo.getCommentCount()
					+ getResources().getString(R.string.comment_title));
		}

		private String createEditorAuthorStr(CityNewsInfo cityNewsInfo){
			StringBuilder sb = new StringBuilder();
			String dot = getResources().getString(R.string.dot);
			if(StringUtil.isEmptyString(cityNewsInfo.getSourceName())){
				//作者不需要显示
//				if(!StringUtil.isEmptyString(cityNewsInfo.getAuthor())){
//					sb.append(cityNewsInfo.getAuthor());
//					sb.append(" "+dot+" ");
//				}
			}else{
//				if(!StringUtil.isEmptyString(cityNewsInfo.getSourceAuthor())){
//					sb.append(cityNewsInfo.getSourceAuthor());
//					sb.append(" "+dot+" ");
//				}
			}

			sb.append(AppUtils.getDateStr(getContext(),cityNewsInfo.getDateGmt()));

			if(cityNewsInfo.getCategory()!=null &&cityNewsInfo.getCategory().length>0){
				//sb.append(" "+dot+" ");
				//sb.append(cityNewsInfo.getCategory()[0]);
			}

			return sb.toString();
		}

		private String createUserAuthorStr(CityNewsInfo cityNewsInfo){
			StringBuilder sb = new StringBuilder();
			String dot = getResources().getString(R.string.dot);
			sb.append(AppUtils.getDateStr(getContext(),cityNewsInfo.getDateGmt()));

			if(cityNewsInfo.getCategory()!=null &&cityNewsInfo.getCategory().length>0){
				//sb.append(" "+dot+" ");
				//sb.append(cityNewsInfo.getCategory()[0]);
			}

			return sb.toString();
		}

		private void initUserItemView(View convertView, CityNewsInfo cityNewsInfo){
			ViewHolder viewHolder = (ViewHolder) convertView.getTag();
			Picasso.with(imContext).load(cityNewsInfo.getAvatar())
					.placeholder(R.drawable.no_avatar)
					.transform(new CircleTransform())
					.resizeDimen(R.dimen.city_list_head_size, R.dimen.city_list_head_size)
					.into(viewHolder.header);
			viewHolder.source.setText(cityNewsInfo.getAuthor());
			viewHolder.author.setText(createUserAuthorStr(cityNewsInfo));

			viewHolder.title.setText(cityNewsInfo.getTitle());// +" | "+cityNewsInfo.getContentSummary());
//			viewHolder.upvote.setTag(cityNewsInfo);
//			if ("Y".equals(cityNewsInfo.getUserUpvoted())) {
//				Drawable drawable = getResources().getDrawable(R.drawable.citynews_item_icon_like_active);
//				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//				viewHolder.upvote.setCompoundDrawables(drawable,null , null, null);
//
//			}else{
//				Drawable drawable = getResources().getDrawable(R.drawable.citynews_item_icon_like);
//				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//				viewHolder.upvote.setCompoundDrawables(drawable,null , null, null);
//			}
//			viewHolder.upvote.setText(cityNewsInfo.getUpvoteCount()==0?getResources().getString(R.string.upvote):cityNewsInfo.getUpvoteCount()+"");

//			viewHolder.commentCount.setTag(cityNewsInfo);
//			viewHolder.commentCount.setText(cityNewsInfo.getCommentCount()==0?getResources().getString(R.string.comment_title):cityNewsInfo.getCommentCount()+"");

			viewHolder.upvote.setTag(cityNewsInfo);
			viewHolder.upvote.setText(" " + getContext().getString(R.string.dot)+ " "
					+ cityNewsInfo.getUpvoteCount()
					+ getResources().getString(R.string.dot_upvote));

			viewHolder.commentCount.setTag(cityNewsInfo);
			viewHolder.commentCount.setText(" " + getContext().getString(R.string.dot)+ " "
					+ cityNewsInfo.getCommentCount()
					+ getResources().getString(R.string.comment_title));

			int imgCount = cityNewsInfo.getUserpostAttachmentImages()==null?0:cityNewsInfo.getUserpostAttachmentImages().size();
			if(imgCount==0){
				viewHolder.imgsLayout.setVisibility(View.INVISIBLE);
			}else{
				viewHolder.imgsLayout.setVisibility(View.VISIBLE);
				for(int i = 0;i<viewHolder.imgs.size();i++){
					ImageView view = viewHolder.imgs.get(i);
					if(i<imgCount){
						view.setVisibility(View.VISIBLE);
						Picasso.with(imContext).load(cityNewsInfo.getUserpostAttachmentImages().get(i)).placeholder(R.drawable.no_image)
								.resizeDimen(R.dimen.citynews_item_imgs_size, R.dimen.citynews_item_imgs_size)
								.into(view);
						if(i==(viewHolder.imgs.size()-1)){
							((CoverImageView)view).setText("+"+(imgCount-3));
						}
					}else{
						view.setVisibility(View.GONE);
					}
				}
			}
		}

		private void initItemView(View convertView, CityNewsInfo cityNewsInfo,int type) {
			if(ITEM_TYPE_USER_POST == type){
				initUserItemView(convertView, cityNewsInfo);
			}else{
				initEditorItemView(convertView,cityNewsInfo);
			}
		}

		public class ViewHolder {
			@Bind(R.id.header)
			ImageView header;
			@Bind(R.id.source)
			TextView source;
			@Bind(R.id.author)
			TextView author;
			@Bind(R.id.title)
			TextView title;
			@Bind(R.id.upvote)
			TextView upvote;
			@Bind(R.id.commentCount)
			TextView commentCount;
			@Bind(R.id.imgs)
			LinearLayout imgsLayout;

			private List<ImageView> imgs;

			public ViewHolder(View view) {
				ButterKnife.bind(this, view);
				imgs = new ArrayList<>();
				int count = imgsLayout.getChildCount();
				for(int i = 0;i<count;i++){
					imgs.add((ImageView) imgsLayout.getChildAt(i));
				}
			}

			@OnClick(R.id.upvote)
			public void onUpvoteClick(View view) {
				CityNewsInfo cityNewsInfo = (CityNewsInfo) view.getTag();
				handleUpvoteCLick(cityNewsInfo);
			}

			@OnClick(R.id.commentCount)
			public void onCommentCountClick(View view) {
				CityNewsInfo cityNewsInfo = (CityNewsInfo) view.getTag();
				handleCommentCountClick(cityNewsInfo);
			}
		}

		public class EditorViewHolder {
			@Bind(R.id.header)
			ImageView header;
			@Bind(R.id.source)
			TextView source;
			@Bind(R.id.author)
			TextView author;
			@Bind(R.id.title)
			TextView title;
			@Bind(R.id.attachmentImage)
			ImageView attachmentImage;
		//	@Bind(R.id.content)
			//TextView content;
			@Bind(R.id.upvote)
			TextView upvote;
			@Bind(R.id.commentCount)
			TextView commentCount;

			public EditorViewHolder(View view) {
				ButterKnife.bind(this, view);
			}

			@OnClick(R.id.upvote)
			public void onUpvoteClick(View view) {
				CityNewsInfo cityNewsInfo = (CityNewsInfo) view.getTag();
				handleUpvoteCLick(cityNewsInfo);
			}

			@OnClick(R.id.commentCount)
			public void onCommentCountClick(View view) {
				CityNewsInfo cityNewsInfo = (CityNewsInfo) view.getTag();
				handleCommentCountClick(cityNewsInfo);
			}
		}
	}


	private void handleUpvoteCLick(CityNewsInfo cityNewsInfo){
		UserInfo userInfo = bModule.getCacheManager().getUserInfo();
		String userId = null;
		String auid = null;
		if (userInfo != null) {
			userId = userInfo.getUserID();
		} else {
			auid = imContext.getSharedPrefManager().getAuid();
		}


		if ("Y".equals(cityNewsInfo.getUserUpvoted())) {
			UserDeleteUpvoteTaskMark taskMark = bModule.getTaskMarkPool().getUserDeleteUpvoteTaskMark(cityNewsInfo.getId(), "post", cityNewsInfo.getId());
			bModule.getServiceWrapper().userDeleteUpvote(CityNewsListView.this, taskMark, userId, auid, cityNewsInfo.getId(), "post");
		} else {
			UserUpvoteTaskMark taskMark = bModule.getTaskMarkPool().getUserUpvoteTaskMark(cityNewsInfo.getId(), "post", cityNewsInfo.getId());
			bModule.getServiceWrapper().userUpvote(CityNewsListView.this, taskMark, userId, auid, cityNewsInfo.getId(), "post");
		}
	}

	private void handleCommentCountClick(CityNewsInfo cityNewsInfo){
		if (!AppUtils.getLoginStatus(getContext())) {
			return;
		}

		Intent intent = new Intent(getContext(),CityNewsDetailActivity.class);
		intent.putExtra("postId",cityNewsInfo.getId());
		intent.putExtra("post_comment","post_comment");
		getContext().startActivity(intent);
	}
}
